package com.sx.baseproject.framework.net.base;

import android.text.TextUtils;

import com.example.mvvm.base.cache.CacheUtils;
import com.example.mvvm.base.cache.FToken;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class GetBaseRequest extends BaseRequest{
    private Map<String, String> map;

    public GetBaseRequest() {
        super.isGet=true;
    }
    private Map<String, String> getMap() {
        if (map == null) {
            map = new HashMap<>();
        }
        return map;
    }

    public GetBaseRequest add(String key, Object value) {
        if (value != null) {
            String res = value.toString();
            if(TextUtils.isEmpty(res)){
                return this;
            }
            map = getMap();
            map.put(key,res );
        }
        return this;
    }


    public Map<String, String> toGetParam() {
        Map<String, String> keyAndValue = new HashMap<>();
        FToken token = CacheUtils.getToken();
        if (token != null) {
            keyAndValue.put("token", token.token);
        }else{
            keyAndValue.put("token", "");
        }
        Class<? extends GetBaseRequest> aClass = this.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            try {
                if(!declaredField.getName().equals("map")){
                    if (declaredField.get(this) != null && !TextUtils.isEmpty(String.valueOf(declaredField.get(this)))) {
                        keyAndValue.put(declaredField.getName(), String.valueOf(declaredField.get(this)));
                    }
                }

            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if (map != null) {
            keyAndValue.putAll(getMap());
        }
        return keyAndValue;
    }

}
